<template>
    <div class="baohutong_account">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form">
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item prop="loginNo">
                            <!-- todo:商城名称查询 -->
                            <el-input v-model.trim="form.loginNo" placeholder="输入登录号查询" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="shopId">
                            <!-- todo:商城名称查询 -->
                            <el-input v-model.trim="form.shopId" placeholder="输入门店ID/门店名称查询" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="tenantId">
                            <!-- todo:商城名称查询 -->
                            <el-input v-model.trim="form.tenantId" placeholder="输入商户ID/商城名称查询" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="name" label="主体名称">
                            <!-- todo:商城名称查询 -->
                            <el-input v-model.trim="form.name" placeholder="输入姓名/企业名称查询" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!-- todo:开通状态 -->
                        <el-form-item label="开通状态" prop="accountStatus">
                            <el-select v-model="form.accountStatus" placeholder="请选择">
                                <el-option
                                    v-for="item in accountStatusList"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="账户类型" prop="accountType">
                            <el-select v-model="form.accountType" placeholder="请选择">
                                <el-option
                                    v-for="item in accountTypes"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="开户时间" prop="createdAt">
                            <el-date-picker
                                v-model="form.createdAt"
                                type="datetimerange"
                                clearable
                                range-separator="至"
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 列表 -->
        <div class="baohutong_account_main">
            <el-table class="baohutong-table" :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <template v-if="prop === 'name'"> {{ row?.name || '-' }}<br />{{ row?.loginNo }} </template>
                        <template v-if="prop === 'tenantInfo'">
                            <span v-for="item in row?.tenantInfo" :key="item.id">
                                <span>商户ID：{{ item.id }}</span
                                ><br />
                                <span>商城名称：{{ item.name }}</span
                                ><br />
                            </span>
                            <span v-if="!row?.tenantInfo || !row?.tenantInfo?.length">-</span>
                        </template>
                        <template v-if="prop === 'shopInfo'">
                            <span v-for="item in row?.shopInfo" :key="item.id">
                                <span>门店ID：{{ item.id }}</span
                                ><br />
                                <span>门店名称：{{ item.name }}</span
                                ><br />
                            </span>
                            <span v-if="!row?.shopInfo || !row?.shopInfo?.length">-</span>
                        </template>
                        <template v-if="['withdrawableAmount', 'settledAmount'].includes(prop)">
                            <!-- 已开户才展示，未开始显示【-】 -->
                            <div class="custom-el-link" v-if="getSum(row, prop)">
                                <span @click="nameRouteHandler(row)"
                                    >￥{{ floatDivide(row[prop], 100).toFixed(2) }}</span
                                >
                            </div>
                            <div v-else>
                                <span>-</span>
                            </div>
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                class="table-button"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <Pagination
                style="margin-top: 15px"
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-account-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="240"
            :visible="popoverVisible">
            <div
                class="custom-account-popover-class-main"
                v-click-outside="onClickOutside"
                v-if="[''].includes(currentRow.ref)">
                <!-- 已报备、已签约 -->
                <h3 style="margin-bottom: 16px">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>
                    <!-- 已报备 -->
                    <template v-if="currentRow.ref == 'removeButtonRef'">该账户微信报备已成功吗？</template>
                    <!-- 已签约 -->
                    <template v-if="currentRow.ref == 'enableButtonRef'">该账户开户意愿已确认吗？</template>
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
        </el-popover>
        <SettingDialog ref="settingRef" @handle-confirm="queryListHandler" />
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, floatDivide, cloneDeep } from '@/commons/utils';
import Pagination from '@/components/Pagination.vue';
import SettingDialog from './settingDialog.vue';

const router = useRouter();
const statusList = reactive(packSelectObjUtil(constants.ACCOUNT_STATUS));
const accountStatusList = [statusList[0], statusList[4], statusList[5], statusList[1], statusList[2], statusList[3]];
const accountTypes = reactive(packSelectObjUtil(constants.ACCOUNT_TYPE));
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];

const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //默认每页15条
    name: '', // 主体名称
    shopId: null, //门店id或名称
    accountStatus: 0, //开通状态： 8;//已开户_待报备 11;//已开户_待绑卡 13;//已绑卡（个体）
    accountType: 0, //账户类型 1 企业账户 2 个体账户 3 个人账户
    createdAt: null //  数组格式的时间
});
let formClone = cloneDeep(form);
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '账户类型', prop: 'accountTypeName', width: '120' },
        { label: '主体名称/登录号', prop: 'name', showOverflowTooltip: true, minWidth: '200' },
        { label: '关联商户', prop: 'tenantInfo', showOverflowTooltip: true, minWidth: '200' },
        { label: '关联门店', prop: 'shopInfo', showOverflowTooltip: true, minWidth: '200' },
        { label: '开通状态', prop: 'accountStatusNameText', width: '140' },
        { label: '可提现金额', prop: 'withdrawableAmount', showOverflowTooltip: true, minWidth: '120' },
        { label: '待结算金额', prop: 'settledAmount', showOverflowTooltip: true, minWidth: '100' },
        { label: '开户时间', prop: 'createdAt', width: '200' },
        { label: '操作', prop: 'operations', width: '80', fixed: 'right' }
    ];
    return baseTableColumns;
});

const nameRouteHandler = ({ loginNo }) => {
    // todo:不同页面
    // settledAmount待结算 withdrawableAmount可提现金额
    router.push({
        path: '/pay/baofutong/detail',
        query: {
            no: loginNo,
            activeName: 'account'
        }
    });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryListHandler();
};

/**
 * 分页查询
 */
const queryListHandler = async () => {
    const _form = cloneDeep(form);
    if (_form.accountStatus == 11) {
        _form.accountStatus = [11, 12];
    } else {
        _form.accountStatus = _form.accountStatus ? [_form.accountStatus] : null;
    }
    _form.accountType = _form.accountType || null;
    const res = await request('baofuAccountAll', _form);
    const list = (res?.data?.data || []).map(item => {
        const { status, accountType, accountStatus } = (item.couponInfo || [])?.[0] || {};
        // 根据不同状态显示不同按钮
        // 3已失效 4已过期 5未启用 6已启用
        const btns = [
            // { label: '详情', fn: routerHandler, ref: 'infoButtonRef', auth: 'coupon_list:query' },
            { label: '设置', fn: setHandler, ref: 'editButtonRef', auth: 'coupon_list:edit' },
            { label: '已报备', fn: reportHandler, ref: 'spreadButtonRef', auth: 'coupon_list:spread' },
            { label: '已签约', fn: enableHandler, ref: 'enableButtonRef', auth: 'coupon_list:enable' }
        ];
        item.accountStatusNameText = item.accountStatusName || '-';
        item.operations = [];
        if (accountType == 2) {
            // 个体账户
            if (accountStatus == 8) {
                // 8.已开户_待报备，13.已绑卡
                item.operations.push(btns[1]);
            } else if (status == 9) {
                // 9.已报备
                item.operations.push(btns[2]);
            }
        }
        item.operations.push(btns[0]);
        return item;
    });
    // todo:已报备已签约按钮，个体户
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.total;
};
// 是否显示金额
const getSum = (row, prop) => {
    let status = false;
    if (row?.accountType == 1) {
        status = [8, 9, 10].includes(row.accountStatus);
    } else if (row?.accountType == 2) {
        status = [8, 9, 10, 12, 13].includes(row.accountStatus);
    } else if (row?.accountType == 3) {
        status = [11, 12, 13].includes(row.accountStatus);
    }
    return status && ![null, undefined].includes(row[prop]);
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};
/** 按钮组操作 */
const popoverHandler = (row, ref) => {
    Object.assign(currentRow, row);
    currentRow.ref = ref;
    buttonRef.value = itemRefs[`${ref}${row.id}`];

    nextTick(() => {
        popoverVisibleHandler(true);
    });
};
// 编辑
let settingRef = ref();
const setHandler = row => {
    settingRef?.value.openDialog(row);
};
// 已签约
const enableHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 已报备
const reportHandler = (row, ref) => {
    popoverHandler(row, ref);
};

// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    let method = null;
    let params = null;
    if (currentRow.ref == 'disableButtonRef') {
        // 失效
        method = 'couponExpireServ';
        params = { id: currentRow.id, couponStatus: 3 };
    } else if (currentRow.ref == 'enableButtonRef') {
        // 启用
        method = 'couponEnable';
        params = { id: currentRow.id };
    } else if (currentRow.ref == 'removeButtonRef') {
        // 删除
        method = 'couponDestroy';
        params = { id: [currentRow.id] };
    }

    await request(method, params);
    popoverVisibleHandler();
    queryListHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

//切换tab筛选
const tabHandler = () => {
    searchHandler();
};

const visibilitychange = () => {
    // 页面可见
    if (document.visibilityState === 'visible') {
        queryListHandler();
    }
};

const getAllData = () => {
    queryListHandler();
};

onMounted(() => {
    // Object.keys(formClone || {})?.forEach(key => {
    //     form[key] = formClone[key];
    // });
    getAllData();
});
onDeactivated(() => {});

onBeforeRouteLeave((to, from, next) => {
    // if (!/\/marketing\/coupon/.test(to?.path)) {
    //     Object.keys(formClone || {})?.forEach(key => {
    //         form[key] = formClone[key];
    //     });
    // }
    next();
});
</script>

<style lang="scss">
.custom-account-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px !important;
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }
}
.baohutong-table {
    color: #33302d;

    font-family: PingFangSC-Regular, PingFang SC;
    font-size: 14px;
    font-weight: 400;
    .el-button--small {
        color: #33302d;
        border: 1px solid #eaeaea;

        font-family: PingFangSC-Regular, PingFang SC;
        font-size: 12px;
        font-weight: 400;
    }
    .el-button--small + .el-button--small {
        margin-left: 8px;
    }
    .el-table__cell {
        padding: 20px 0;
    }

    th.el-table__cell {
        color: #33302d;

        font-family: PingFangSC-Medium, PingFang SC;
        font-size: 14px;
        font-weight: 500;
    }
}
</style>
<style lang="scss" scoped>
$colors: #cccccc, #ff6b00, #cccccc, #ffd500, #cccccc, #ff6b00;

.baohutong_account {
    &_top {
        margin-bottom: 16px;
        padding: 24px;

        background-color: #fff;
    }
    &_header {
        overflow: hidden;
        :deep {
            .el-col-8 {
                overflow: hidden;

                margin-bottom: -500px;
                padding-bottom: 512px;
                &:last-of-type {
                    & > div {
                        margin-right: 0;
                    }
                }
            }
        }
        &_item {
            position: relative;

            display: flex;
            overflow: hidden;
            align-items: center;
            justify-content: space-between;

            margin-right: 15px;
            margin-bottom: -500px;
            padding: 24px;
            padding-bottom: 512px;

            background: #fff6ef;
            h3,
            p {
                margin: 0;
            }
            h3 {
                display: flex;
                align-items: center;

                color: #33302d;

                font-family: PingFangSC-Medium, PingFang SC;
                font-size: 16px;
                font-weight: 500;
                :deep(.el-icon) {
                    margin-left: 4px;

                    color: #33302d;
                }
            }
            p {
                margin-top: 16px;

                color: #666666;

                font-family: PingFangSC-Regular, PingFang SC;
                font-size: 14px;
                font-weight: 400;
                line-height: 20px;
            }
            & > div {
                // margin-right: 118px;
            }
            :deep(.el-button) {
                position: absolute;
                top: 24px;
                right: 24px;
            }
        }
    }
    :deep(.el-tabs__item) {
        font-size: 16px !important;
    }
    :deep {
        .el-tabs__nav-wrap {
            margin-bottom: -15px;
            &::after {
                height: 0;
            }
        }
    }
    &_bottom {
        padding: 24px;

        background-color: #fff;
    }
    .zw-form-layout {
        margin-bottom: 16px;
        background: #fff;
        border: 0;
    }
    .not-started {
        color: #aaa;
    }

    &_main {
        min-height: calc(100vh - 335px);
        box-sizing: border-box;
        padding: 24px;
        background-color: #fff;
        overflow-y: auto;
    }

    .custom-el-link {
        overflow: hidden;

        white-space: nowrap;
        text-overflow: ellipsis;

        color: rgb(255, 107, 0);
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }

    .custom-el-link {
        overflow: hidden;

        white-space: nowrap;
        text-overflow: ellipsis;

        color: rgb(255, 107, 0);
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }

    @for $i from 1 to 7 {
        .custom-status-#{$i} {
            position: relative;

            padding-left: 14px;
            &::before {
                position: absolute;
                top: 50%;
                left: 0px;

                width: 8px;
                height: 8px;

                content: '';
                transform: translateY(-50%);

                border-radius: 50%;
                background: nth($colors, $i);
            }
        }
    }
}
</style>
